package com.dxtan90.strategy.impl;

import com.dxtan90.strategy.BaseStrategy;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author shijunhao
 * @since 2024/4/16 14:03
 */
public class Biqudi extends BaseStrategy {

    @Override
    public String getSourceUrl() {
        return "https://www.biqudi.cc";
    }

    @Override
    public String getCategoryName() {
        return "biqudi";
    }

    @Override
    public String parseTitle(Document document) {
        return Optional.ofNullable(document.getElementById("info"))
                .map(element -> element.child(0))
                .map(Element::text)
                .orElse("noneTitle_" + System.currentTimeMillis());
    }

    @Override
    public List<String> parseCategory(Document document) {
        List<String> category = new ArrayList<>();
        Elements dds = Optional.ofNullable(document.getElementById("newlist"))
                .map(Element::children)
                .orElse(new Elements());
        for (org.jsoup.nodes.Element dd : dds) {
            Optional.of(dd.child(0)).ifPresent(a -> {
                String href = a.attr("href");
                category.add(href);
            });
        }
        return category;
    }

    @Override
    public List<String> parseContent(Document document) throws IOException {
        List<String> sectionList = new ArrayList<>();
        Elements novels = Optional.ofNullable(document.getElementById("booktxt"))
                .map(article -> article.getElementsByTag("p"))
                .orElse(new Elements());
        novels.forEach(p -> sectionList.add(p.text()));

        Elements nexts = document.select("a[rel=next]");
        Element next = nexts.get(0);
        if ("下一页".equals(next.text())) {
            String href = next.attr("href");
            sectionList.addAll(getDocument(getSourceUrl() + href));
        }
        return sectionList;
    }

}